package com.ubing.boot.notesforjava.test.juc;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName : MyCountainer
 * @Description : MyCountainer
 * @Author : Xxxxx
 * @Date: 2023-03-14 11:16
 */
public class MyContainer<T> {
    final private LinkedList<T> lists =  new LinkedList();
    final private int MAX =10;
    private int count=0;

    public synchronized void put(T t){
        while (count==MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lists.add(t);
        ++count;
        this.notifyAll();
    }

    public synchronized T get(){
        T t=null;
        while (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t=lists.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        MyContainer<String> container=new MyContainer<>();
        // 启动消费者线程
        for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                for (int j = 0; j <5 ; j++) {
                    System.out.println(Thread.currentThread().getName()+"=="+container.get());
                }
            },"c"+i).start();
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 启动生产者线程
        for (int i = 0; i <2 ; i++) {
            new Thread(()->{
                for (int j = 0; j < 25; j++) {
                    container.put(Thread.currentThread().getName()+"--"+j);
                }
            },"p"+i).start();
        }
    }
}
